package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.dto.IdDTO;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AddressBookServiceImpl implements AddressBookService {

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Override
    public void save(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookMapper.save(addressBook);
    }

    @Override
    public List<AddressBook> list() {
        Long UserId = BaseContext.getCurrentId();
        List<AddressBook> list = addressBookMapper.list(UserId);
        return list;
    }

    @Override
    public AddressBook getDefault() {
        Long userId = BaseContext.getCurrentId();
        AddressBook addressBook =  addressBookMapper.getDefault(userId);
        return addressBook;
    }

    @Override
    public void update(AddressBook addressBook) {
        addressBookMapper.update(addressBook);
    }

    @Override
    public void delete(Long id) {
        addressBookMapper.delete(id);
    }

    @Override
    public AddressBook getById(Long id) {
        AddressBook addressBook = addressBookMapper.getById(id);
        return addressBook;
    }

    @Override
    public void setDefaultById(IdDTO id) {
        AddressBook address = addressBookMapper.getDefaultAddress();
        if (address != null){
            Long defaultId = address.getId();
            addressBookMapper.updateDefault(defaultId);
        }
        addressBookMapper.setDefaultById(id);
    }
}
